package ReflectTest03;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
反射获取成员方法并使用的练习
Student s=new Student();
s.method1();
s.method2("姜恒星")
String ss=s.method3("姜恒星",30);
System.out.println(ss);
s.function()
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c = Class.forName("Reflect.Student");
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

        Method method1 = c.getMethod("method1");
        method1.invoke(obj);
        Method method2 = c.getMethod("method2", String.class);
        method2.invoke(obj,"姜恒星");
        Method method3 = c.getMethod("method3", String.class, int.class);
        Object o = method3.invoke(obj, "姜恒星", 30);
        System.out.println(o);
//        String ss = method3.toString();

        //s.function();
//        Method m4 = c.getMethod("function");//NoSuchMethodException不是公共的
        Method m4 = c.getDeclaredMethod("function");
        m4.setAccessible(true);
        m4.invoke(obj);//无参，无返回值
    }
}
